<template>
  <div class="boxCard">
    <!-- 左侧 -->
    <div class="left">
      <el-card shadow="always" style="width: 100%; height: 100%">
        <div class="header">
          <div class="title">
            <span></span>
            <p>集合</p>
          </div>

          <div>
            <el-button type="primary" size="small" @click="addDatabase"
              >新增集合</el-button
            >
          </div>
        </div>

        <div style="height: 78vh">
          <el-input
            v-model="tableName"
            placeholder="请输入表名"
            clearable
            style="width: 100%"
            @keyup.enter.native="getDatabaseInfo"
          />
          <div class="tableList">
            <div
              v-for="(item, index) in basebaseList"
              :key="index"
              class="database"
              :class="radio === index ? 'active' : ''"
              @click="radioChange(index)"
            >
              <p>{{ item.databaseName }}</p>
              <div class="operation">
                <i @click="lookDatabase(item)" class="el-icon-info"></i>
                <i
                  style="margin-left: 10px"
                  class="el-icon-delete-solid"
                  @click="delDatabase(item)"
                ></i>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 右侧 -->
    <div class="right">
      <el-card shadow="always" style="height: 30%">
        <div class="title">
          <span />
          <p>查询条件</p>
        </div>

        <el-form :model="seachForm" label-width="120px">
          <el-row :gutter="12">
            <el-col
              v-for="(item, index) in titles"
              v-show="index < 8"
              :key="index"
              :span="6"
            >
              <el-form-item :label="item.name">
                <el-input
                  v-model="seachForm[item.prop]"
                  :placeholder="`请输入${item.name}`"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24" style="text-align: right">
              <el-button type="primary" @click="radioChange">查询</el-button>
              <el-button @click="rest">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <el-card shadow="always" style="margin-top: 12px; height: 67%">
        <div class="header">
          <div class="title">
            <span />
            <p>表数据及结构</p>
          </div>

          <div>
            <uploadFile
              text="导入数据"
              action="/api/api/uploadDatabase"
              :data="uploadParmse"
              @success="fileUpload_success"
            ></uploadFile>
          </div>
        </div>

        <el-table
          v-loading="tableLoading"
          :data="tableList"
          height="45vh"
          element-loading-text="加载中..."
          border
          ref="table"
        >
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="80"
            fixed="left"
          />

          <!-- 便利表头 -->
          <el-table-column
            v-for="(item, index) in titles"
            :key="index"
            :label="item.name"
            align="center"
            show-overflow-tooltip
            width="200"
          >
            <template slot-scope="scope">
                <span>{{typeof scope.row[item.prop] == 'object' ? '对象文档' : (scope.row[item.prop] || '----')}}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="titles.length == 0"></el-table-column>

          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="150"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="edit(scope.row)">修改</el-button>

              <el-button type="text" @click="del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 10px">
          <el-pagination
            :current-page="seachForm.page"
            :page-sizes="[10, 50, 100, 200]"
            :page-size="seachForm.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="seachForm.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 修改 -->
    <el-dialog :visible.sync="isShowEdit" title="修改">
      <el-form :model="editObj" label-width="120px">
        <el-row :gutter="12">
          <el-col
            v-for="(item, index) in titles"
            v-show="item.name != 'id' && item.name != '_id'"
            :key="index"
            :span="24"
          >
            <el-form-item :label="item.name">
              <el-input
                v-model="editObj[item.prop]"
                :placeholder="`请输入${item.name}`"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: center">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="isShowEdit = false">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 查看数据库 -->
    <el-dialog :visible.sync="isShowLookDatabase" title="查看数据库">
      <el-form :model="databaseInfo" label-width="120px" disabled>
        <el-row :gutter="12">
          <el-col :span="24">
            <el-form-item label="数据库名称：">
              <span>{{ databaseInfo.databaseName }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="数据库大小：">
              <span>{{ databaseInfo.size }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="文档数量：">
              <span>{{ databaseInfo.count }}条</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 新增数据库 -->
    <el-dialog :visible.sync="isShowEditAddDatabase" title="新增数据库">
      <el-form :model="addDatabaseObj" label-width="120px">
        <el-form-item label="数据库名称：">
          <el-input
            v-model="addDatabaseObj.databaseName"
            placeholder="请输入数据库名称"
          ></el-input>
        </el-form-item>

        <div style="text-align: center">
          <el-button type="primary" @click="confirmAddDatabase">确定</el-button>
          <el-button @click="isShowEditAddDatabase = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 删除数据库 -->
    <el-dialog :visible.sync="isShowDelDatabase" title="删除数据库">
      <p style="color: red">
        您正在进行危险操作，请输入”
        <span style="background: #ffd43b; color: #333; padding: 2 6px">{{
          delDataBaseParmse.databaseName
        }}</span
        >“ 来删除数据库
      </p>
      <el-input
        v-model="databaseName"
        placeholder="请输入数据库名称"
      ></el-input>

      <div style="text-align: center; margin-top: 15px">
        <el-button @click="confirmDelDatabase" type="primary">确定</el-button>
        <el-button @click="isShowDelDatabase = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDataBase,
  deleteDatabase,
  delTableData,
  getDatBaseInfo,
  getTableData,
  saveTableData,
} from "@/api/databaseManagement";
import uploadFile from "@/components/uploadFile";
import TableView from "@/components/TableView/index.vue";

export default {
  data() {
    return {
      radio: 0,
      basebaseList: [],
      titles: [],
      tableList: [],
      tableLoading: false,
      tableName: "",
      seachForm: {
        size: 10,
        page: 1,
        total: 0,
      },

      // 修改数据
      isShowEdit: false,
      editObj: {},

      // 查看数据库信息
      isShowLookDatabase: false,
      databaseInfo: {},

      // 新增数据库
      isShowEditAddDatabase: false,
      addDatabaseObj: {},

      // 上传文件携带参数
      uploadParmse: {},

      // 删除数据库
      isShowDelDatabase: false,
      databaseName: "",
      delDataBaseParmse: {},
    };
  },

  components: {
    uploadFile,
    TableView,
  },

  mounted() {
    this.getDatabaseInfo();
  },

  methods: {
    // 获取表信息
    async getDatabaseInfo() {
      const result = await getDatBaseInfo({ databaseName: this.tableName });
      if (result.code == 20000) {
        this.basebaseList = result.data;
        if (this.basebaseList.length != 0) {
          if (this.radio != 0) {
            this.radio = this.basebaseList.length < this.radio ? 0 : this.radio;
          }
          this.uploadParmse.databaseName = this.basebaseList[0].databaseName; //数据库名称
          this.radioChange();
        }
      }
    },

    // 单选框发生变化
    async radioChange(index) {
      if (index == this.radio) return;
      if (index >= 0) {
        this.radio = index;

        //数据库名称
        this.uploadParmse.databaseName =
          this.basebaseList[this.radio].databaseName;
      }

      this.tableLoading = true;
      const { databaseName } = this.basebaseList[this.radio];
      const result = await getTableData({
        databaseName: databaseName,
        ...this.seachForm,
      });
      if (result.code == 20000) {
        this.tableList = result.data;
        this.seachForm.total = result.total;
        this.titles = [];
        if (result.data.length != 0) {
          for (const key in result.data[0]) {
            this.titles.push({
              prop: key,
              name: key,
            });
          }
        }

        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      } else {
        this.$message.error(result.msg);
      }
      this.tableLoading = false;
    },

    // 删除数据库
    delDatabase(item) {
      this.isShowDelDatabase = true;
      this.databaseName = "";
      this.delDataBaseParmse = { ...item };
    },

    confirmDelDatabase() {
      if (!this.databaseName) {
        this.$message.warning("请输入数据库名称");
        return;
      }

      if (this.databaseName != this.delDataBaseParmse.databaseName) {
        this.$message.warning("数据库名称输入错误");
        return;
      }

      this.$confirm(
        `当前数据库下有${this.delDataBaseParmse.count}条数据，确定删除吗？`,
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      ).then(async () => {
        const res = await deleteDatabase({
          databaseName: this.delDataBaseParmse.databaseName,
        });
        if (res.code == 20000) {
          this.$message.success("删除成功");
          this.getDatabaseInfo();
        } else {
          this.$message.error(res.msg);
        }

        this.isShowDelDatabase = false;
      });
    },

    // 新增数据库
    addDatabase() {
      this.addDatabaseObj = {};
      this.isShowEditAddDatabase = true;
    },

    // 新增数据库确定按钮
    async confirmAddDatabase() {
      if (!this.addDatabaseObj.databaseName) {
        this.$message.warning("请输入数据库名称");
        return;
      }

      try {
        let result = await addDataBase({
          databaseName: this.addDatabaseObj.databaseName,
        });

        if (result.code == 20000) {
          this.$message.success(result.msg);
          this.isShowEditAddDatabase = false;
          this.getDatabaseInfo();
        } else {
          this.$message.error(result.msg);
        }
      } catch (error) {
        this.$message.error("系统异常，请联系管理员" + error);
      }
    },

    // 文件上传成功
    fileUpload_success(e) {
      console.log(e);
      if (e.res.code == 20000) {
        this.getDatabaseInfo();
        this.$message.success(e.res.msg);
      } else {
        this.$message.error(e.res.msg);
      }
    },

    rest() {
      this.seachForm = {};
      this.radioChange();
    },

    // 查看数据库
    lookDatabase(item) {
      console.log("ddas");
      this.isShowLookDatabase = true;
      this.databaseInfo = { ...item };
    },

    // 修改按钮
    edit(item) {
      this.isShowEdit = true;
      this.editObj = { ...item };
    },

    // 删除按钮
    del(item) {
      this.$confirm("确定删除这条数据吗？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      }).then(async () => {
        try {
          let result = await delTableData({
            databaseName: this.basebaseList[this.radio].databaseName, //数据库名称
            id: item.id,
          });

          if (result.code == 20000) {
            this.$message.success(result.msg);
            this.radioChange();
          } else {
            this.$message.error(result.msg);
          }
        } catch (error) {
          this.$message.error(error);
        }
      });
    },

    // 保存按钮
    async save() {
      const result = await saveTableData({
        ...this.editObj,
        databaseName: this.basebaseList[this.radio].databaseName,
      });

      if (result.code == 20000) {
        this.$message.success(result.msg);
        this.radioChange();
      } else {
        this.$message.error(result.msg);
      }

      this.isShowEdit = false;
    },

    // 分页
    handleCurrentChange(e) {
      this.seachForm.page = e;
      this.radioChange();
    },
    handleSizeChange(e) {
      this.seachForm.size = e;
      this.radioChange();
    },
  },
};
</script>

<style scoped>
.boxCard {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left {
  width: 20%;
  height: 100%;
  overflow-y: auto;
  background: #fff;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.4);
  border-radius: 10px;
  /* padding: 10px; */
  /* box-sizing: border-box; */
}

.right {
  width: 79%;
  height: 100%;
  overflow-y: auto;
  background: #fff;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.4);
  border-radius: 10px;
}

.left-bottom {
  width: 100%;
}

.tableList {
  width: 100%;
  height: calc(100% - 30px);
  overflow-y: auto;
}

.tableList .database {
  width: 100%;
  height: 40px;
  border-radius: 5px;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  box-sizing: border-box;
  font-size: 14px;
  color: #333;
  border: 1px solid #e9ecef;
  cursor: pointer;
}

.tableList .database p {
  width: 70%;
  border-right: 1px solid #e9ecef;
}

.tableList .database i {
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.active {
  border: 1px solid #4dabf7 !important;
}
</style>
